from Acquisition import aq_inner, aq_chain, aq_base

from Products.Five.browser import BrowserView

from Products.CMFPlone.PloneBaseTool import PloneBaseTool, getExprContext
from Products.CMFCore.interfaces import ISiteRoot

from zope.component import getMultiAdapter
from zope.interface import implements

from plone.memoize.view import memoize
from plone.app.layout.globals.portal import PortalState

from plone.app.multilingual.interfaces import ILanguageFolder, ILanguageURL


# XXX: Until policies have been implemented, use a global flag
DEV_POLICY_CHECK = True


class LanguageURL(BrowserView):
    implements(ILanguageFolder)
    
    def __init__(self, context, request):
        super(BrowserView, self).__init__(context, request)
        language_folder = None
        for obj in aq_chain(aq_inner(context)):
            if ILanguageFolder.providedBy(obj):
                language_folder = obj
                break
            if ISiteRoot.providedBy(obj):
                language_folder = obj
                break
        assert language_folder is not None, "Not a portal context!"
        self.language_folder = language_folder
        self.title = self.language_folder.Title()
        
    def __call__(self):
        return self.language_folder.absolute_url()
    
    
# Hook into the expression context to allow alteration of the portal_url
# definition, if policy dictates so.
def _getExprContext(self, object):
    context = getExprContext(self, object)
    if DEV_POLICY_CHECK: # XXX: Insert policy check here
        request = context.getValue('request')
        if request is not None:
            language_url = getMultiAdapter((object, request),
                                           name=u'language_url')()
            context.setContext('portal_url', language_url)
            context.setGlobal('portal_url', language_url)
    return context

PloneBaseTool._getExprContext = _getExprContext


# The plone_portal_state holds a portal URL as well, as well as the title.
class MultiLingualPortalState(PortalState):
    @memoize
    def portal_title(self):
        if DEV_POLICY_CHECK: # XXX: Insert policy check here
            return getMultiAdapter((self.context, self.request),
                                   name=u'language_url').title
        return super(MultiLingualPortalState, self).portal_title()
    
    @memoize
    def portal_url(self):
        if DEV_POLICY_CHECK: # XXX: Insert policy check here
            return getMultiAdapter((self.context, self.request),
                                   name=u'language_url')()
        return super(MultiLingualPortalState, self).portal_url()
